package cn.edu.sdjzu.xg.bysj.controller.basic;

import cn.edu.sdjzu.xg.bysj.domain.School;
import cn.edu.sdjzu.xg.bysj.service.SchoolService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import util.Condition;
import util.ControllerHelper;
import util.JSONUtil;
import util.Pagination;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

@WebServlet("/basic/school.ctl")
@Slf4j
/**
 * 将所有方法组织在一个Controller(Servlet)中
 *根据id查询
 {"id":2}
 *分页查询 模糊查询
 {
 "pagination": {
 "pageNo": 2,
 "pageSize": 2
 },
 "conditionList": [{
 "value": "理",
 "key": "descriptoin",
 "operator": "LIKE"
 }
 ]
 }
 */
/**
 * 将所有方法组织在一个Controller(Servlet)中
 *
 * @author 1033299034@qq.com
 */
public class SchoolController extends HttpServlet {
    public SchoolController(){}
    /**
     * POST, http://localhost:8080/school.ctl, 增加学院
     * 增加一个学院对象：将来自前端请求的JSON对象，增加到数据库表中
     * @param request 请求对象
     * @param response 响应对象
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //设置请求字符编码为UTF-8
        //request.setCharacterEncoding("UTF-8");
        //根据request对象，获得代表参数的JSON字串
        String school_json = JSONUtil.getJSON(request);

        //将JSON字串解析为School对象
        School schoolToAdd = JSON.parseObject(school_json, School.class);

        //设置响应字符编码为UTF-8
        //response.setContentType("application/json;charset=UTF-8");

        //创建JSON对象message，以便往前端响应信息
        JSONObject message = new JSONObject();
        //在数据库表中增加School对象
        try {
            SchoolService.getInstance().add(schoolToAdd);
            message.put("message", "增加成功");
            log.trace("增加成功");

        }catch (SQLException e){
            message.put("message", "数据库操作异常");
            log.error("数据库操作异常" + e.getMessage());

        }catch(Exception e){
            message.put("message", "网络异常");
            log.error("网络异常" + e.getMessage());
        }finally {
            //响应message到前端
            response.getWriter().println(message);
        }
    }

    /**
     *
     * 删除一个学院对象：根据来自前端请求的id，删除数据库表中id的对应记录
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //将request参数转换为JSON字串
        String request_json_str = JSONUtil.getJSON(request);
        //将请求body解析为要删除的ProfTitle的id对应的JSONObject对象(可能是{"id":1})
        JSONObject idOfTeacherToDelete_jsonObj = JSON.parseObject(request_json_str);
        //从JSONObject对象中读取键“id”的值（Java Object对象），
        Object id_obj = idOfTeacherToDelete_jsonObj.get("id");
        int id = Integer.parseInt(id_obj.toString());
        log.trace("删除id" + id);
        //设置响应字符编码为UTF-8
        response.setContentType("application/json;charset=UTF-8");
        //创建JSON对象respMessage_jsonObj，以便往前端响应信息
        JSONObject respMessage_jsonObj = new JSONObject();
        try {
            SchoolService.getInstance().delete(id);
            respMessage_jsonObj.put("message", "删除成功");
            log.trace("删除成功");
        }catch (SQLException e){
            respMessage_jsonObj.put("message", "数据库操作异常");
            log.error("数据库操作异常" + e.getMessage());

        }catch(Exception e){
            respMessage_jsonObj.put("message", "网络异常");
            log.error("网络异常" + e.getMessage());
        }
        finally {
            //响应message到前端
            response.getWriter().println(respMessage_jsonObj);
        }
    }

    /**
     * PUT, http://localhost:8080/school.ctl, 修改学院
     *
     * 修改一个学院对象：将来自前端请求的JSON对象，更新数据库表中相同id的记录
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPut(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //设置请求字符编码为UTF-8
        //request.setCharacterEncoding("UTF-8");
        //根据request对象，获得代表参数的JSON字串
        String school_json = JSONUtil.getJSON(request);
        //将JSON字串解析为School对象
        School schoolToUpdate = JSON.parseObject(school_json, School.class);
        //设置响应字符编码为UTF-8
        response.setContentType("application/json;charset=UTF-8");
        //创建JSON对象message，以便往前端响应信息
        JSONObject message = new JSONObject();
        //到数据库表修改School对象对应的记录
        try {
            SchoolService.getInstance().update(schoolToUpdate);
            message.put("message", "修改成功");
            log.trace("修改成功");
        }catch (SQLException e){
            message.put("message", "数据库操作异常");
            log.error("数据库操作异常" + e.getMessage());
        }catch(Exception e){
            message.put("message", "网络异常");
            log.error("网络异常" + e.getMessage());
        }
        finally {
            //响应message到前端
            response.getWriter().println(message);
        }
    }

    /**
     *查询
     * 把一个或所有学院对象响应到前端
     * 如果请求的是id根据id查询一个
     * 如果没有id 根据对应的分页和条件来查询
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //创建JSON对象respMessage_jsonObj，以便往前端响应信息
        JSONObject respMessage_jsonObj = new JSONObject();

        //设置响应字符编码为UTF-8
        //response.setContentType("application/json;charset=UTF-8");

        //将request body转换为JSON字串
        String req_jsonStr = JSONUtil.getJSON(request);
        //将request body解析为JSONObject对象
        JSONObject req_jsonObj = JSON.parseObject(req_jsonStr);
        //如果请求body为空
        if (req_jsonObj == null) {
            respMessage_jsonObj.put("message","未收到请求信息！");
            response.getWriter().println(respMessage_jsonObj);
            log.error("未收到信息");
            return;
        }
        //从JSONObject对象中读取键“id”的值（Java Object对象），req_jsonObj可能是{"id":？}
        Object id_obj = req_jsonObj.get("id");
        try {
            //如果id_Obj != null, 说明请求数据有id键，是请求某个教师对象
            if (id_obj != null) {
                int id_int = Integer.parseInt(id_obj.toString());
                responseSchool(id_int, response);
                log.trace("查找id为" + id_int + "的学院");
            }else {
                //读取分页信息，形成分页对象 从JSONObject对象中读取 “pagination” 键对应的值(JSONObject对象)
                Pagination pagination = ControllerHelper.getPagination(req_jsonObj);
                //从请求JSONObject对象中读取键“conditionList”对应的值(描述查询条件的JSONArray对象)
                List<Condition> conditionList = ControllerHelper.getConditions(req_jsonObj);
                //响应多个教师信息，其中conditionList, pagination两个对象引用为空是可能的
                this.responseSchools(response, conditionList, pagination);
            }
        }catch (SQLException e){
            respMessage_jsonObj.put("message", "数据库操作异常"+e.getMessage());
            //响应message到前端
            response.getWriter().println(respMessage_jsonObj);
            log.error("数据库操作异常" + e.getMessage());
        }catch(Exception e){
            respMessage_jsonObj.put("message", "网络异常");
            //响应message到前端
            response.getWriter().println(respMessage_jsonObj);
            log.error("message", "网络异常"+ e.getMessage());
        }
    }

    /**
     * 根据id查找
     * @param id
     * @param response
     * @throws ServletException
     * @throws IOException
     * @throws SQLException
     */
    private void responseSchool(int id, HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        //根据id查找学院
        School school = SchoolService.getInstance().find(id);
        String school_json = JSON.toJSONString(school);

        //响应school_json到前端
        response.getWriter().println(school_json);
    }

    /**
     * 根据前台请求查找
     * @param response
     * @param pagination 带有前台请求数据的对象
     * @throws ServletException
     * @throws IOException
     * @throws SQLException
     */
    private void responseSchools(HttpServletResponse response, List<Condition> condition, Pagination pagination)
            throws ServletException, IOException, SQLException {
        //根据请求查询对象
        Collection<School> schools = SchoolService.getInstance().findAll(condition,pagination);
        //将查到的对象集合序列化为JSON格式字串
        String schools_json = JSON.toJSONString(schools, SerializerFeature.DisableCircularReferenceDetect);
        //创建message对象，以便往前台响应信息
        JSONObject message = new JSONObject();
        //元组总数
        message.put("totalNum",pagination.getTotalNum());
        //指定页元组数据
        message.put("data",schools_json);
        //响应message到前端
        response.getWriter().println(message);
    }
}
